// 配置信息
import { defineStore } from "pinia"
import { apiUserInfo } from '@/api/user.js'
import { navigateTo } from '@/utils/router.js'
import { apiGetIntegralProduct } from '@/api/integral-mall.js'

let useUserStore = defineStore("user", {
	state: () => {
		return {
			token: uni.getStorageSync('token') || "",
			userInfo: uni.getStorageSync('userInfo') || null,
			// user_type: 1, // 用户类型 1-用户 2-游客
			integralProduct: uni.getStorageSync('integralProduct') || []
		}
	},
	actions: {
		// 获取用户信息
		async getUserInfo() {
			try {
				const { data: { userInfo } } = await apiUserInfo()
				this.userInfo = userInfo
				uni.setStorageSync('userInfo', userInfo)
				// 获取积分商品 - 有缓存时不请求
				const cachedProduct = uni.getStorageSync('integralProduct');
				if (!Array.isArray(cachedProduct) || cachedProduct.length === 0) {
					this.getIntegralProduct();
				}
			} catch (error) {
				console.log(error, 'error');
			}
		},
		// 获取积分商品
		async getIntegralProduct() {
			try {
				const { data } = await apiGetIntegralProduct({ status: 1, type: 10 })
				this.integralProduct = data.data
				uni.setStorageSync('integralProduct', data.data)
			} catch (error) {
				console.log(error, 'error');
			}
		},
		setToken(val) {
			this.token = val;
			uni.setStorageSync('token', val)
		},
		clearToken() {
			this.token = ''
			uni.setStorageSync('token', this.token)
		},
		clearLoginInfo() {
			this.token = '';
			this.userInfo = null;
			uni.setStorageSync('token', this.token)
			uni.setStorageSync('userInfo', this.userInfo)
			navigateTo('/pages/login/index')
		},
		// 检查登录状态，未登录则跳转到登录页
		checkLogin() {
			if (!this.isLoggedIn) {
				this.clearLoginInfo()
				return false
			}
			return true
		}
	},
	getters: {
		// 判断用户是否已登录
		isLoggedIn(state) {
			return !!state.token && !!state.userInfo
		}
	},
})

export default useUserStore